package validator

import (
	"fmt"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	en_translations "github.com/go-playground/validator/v10/translations/en"
	"log"
)

func RegisterValidate() {
	// 注册验证器
	validate, ok := binding.Validator.Engine().(*validator.Validate)
	if ok {
		validate.RegisterValidation("NotNull", notNullValidator)
	}
}

// 参数不能为空(包括不传参数及参数值为空字符串)
var notNullValidator validator.Func = func(fl validator.FieldLevel) bool {
	if value, ok := fl.Field().Interface().(string); ok {
		// 字段不能为空，并且不等于  admin
		return value != ""
	}
	return true
}

func ValidForm() {
	// 验证器实例
	validate := validator.New()

	// 通用的中文翻译器
	translator := ut.New(en.New(), en.New())

	// 获取英文翻译器
	trans, found := translator.GetTranslator("en")
	if !found {
		log.Fatal("translator not found")
	}

	// 注册错误信息
	if err := en_translations.RegisterDefaultTranslations(validate, trans); err != nil {
		log.Fatal(err)
	}

	// 自定义错误信息
	validate.RegisterTranslation("my_err", trans, func(ut ut.Translator) error {
		return ut.Add("my_err", "{0} must contain only numbers!", true) // 真实情况下，这里的消息应该是本地化的
	}, func(ut ut.Translator, fe validator.FieldError) string {
		t, _ := ut.T("my_err", fe.Field())
		return t
	})

	type RegisterRequest struct {
		Username string `validate:"my_err"` // 使用自定义的验证标签
	}

	request := RegisterRequest{
		Username: "abc",
	}

	// 验证
	err := validate.Struct(request)
	if err != nil {
		// 打印错误信息
		if _, ok := err.(*validator.InvalidValidationError); ok {
			fmt.Println(err)
			return
		}

		for _, err := range err.(validator.ValidationErrors) {
			fmt.Println(err.Namespace())
			fmt.Println(err.Field())
			fmt.Println(err.StructNamespace())
			fmt.Println(err.StructField())
			fmt.Println(err.Tag())
			fmt.Println(err.ActualTag())
			fmt.Println(err.Kind())
			fmt.Println(err.Type())
			fmt.Println(err.Value())
			fmt.Println(err.Param())
			fmt.Println()
		}
	}
}
